#=
测试哈密顿量构造
=#


include("../src/edmary.jl")

using ..edmary

using SparseArrays
using LinearAlgebra
using Arpack: eigs
using Dates
using JLD2


function saveCSC(fh, name)
    if isfile(name)
        rm(name)
    end
    handle = jldopen(name, "w")
    write(handle, "CSC", fh)
    close(handle)
end


function loadCSC(name)
    handle = jldopen(name, "r")
    csc = read(handle, "CSC")
    close(handle)
    return csc
end


function spcd()
    L = 4
    npart = 3
    nsite = L^2
    U = 0.0
    t1 = -1.0
    t2 = -1.5
    name = "L$(L)npart$(npart)nsite$(nsite)U$(U)t1$(t1)t2$(t2).jld"
    sta, invsta = get_state_array(npart, nsite)
    println(length(sta))
    @show Dates.now()
    bonds = bonds_ckb(L, t1, t2)
    if isfile(name)
        fh = loadCSC(name)
    else
        fh = full_hmltCSC(npart, nsite, sta, invsta, bonds, U)
        saveCSC(fh, name)
    end
    @show Dates.now()
    #println(Matrix(fh))
    #
    #nurand = rand(length(sta))
    #nutmp = zeros(length(sta))
    #apply_hmlt!(nutmp, nurand, nsite, sta, invsta, bonds, U)
    #println(nutmp)
    #println(fh*nurand)
    #@show Dates.now()
    #@assert all(isapprox.(nutmp, fh*nurand, atol=1e-10))
    #@show Dates.now()
    #
    v0r = rand(length(sta))
    v0r = v0r / norm(v0r)
    eval, evec = eigs(fh; nev=2, which=:SR, tol=0.0, maxiter=100, sigma=nothing, ritzvec=true, v0=v0r)
    println(eval)
    @show Dates.now()
    #
    #ppbonds = ppbonds_ckb(4,
    #Dict("+x"=>1, "+y"=>-1, "-x"=>1, "-y"=>-1, "+x+y"=>0, "-x-y"=>0),
    #Dict("+x"=>1, "+y"=>-1, "-x"=>1, "-y"=>-1, "+x-y"=>0, "-x+y"=>0),
    #)
    #corr = ppbuild_from_order_param(ppbonds, [1, 5])
    #pp = full_ppCSC(npart, nsite, sta, invsta, corr, U)
    #handle = jldopen("pp.jld", "w")
    #write(handle, "CSC", pp)
    #close(handle)
    handle = jldopen("diswave.jld", "r")
    ppCSC = read(handle, "CSC")
    close(handle)
    println(size(ppCSC))
    gndv = @view(evec[:, 1])
    pvec = ppCSC*gndv
    println(gndv[1:100])
    println(pvec[1:100])
    println(adjoint(gndv)*pvec)
end


spcd()
